package com.rjs.nio.channel;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;

public class ServerSocketChannelDemo {

	public static void main(String[] args) throws IOException {
		ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
		serverSocketChannel.socket().bind(new InetSocketAddress(9999));
		//设置非阻塞模式
		serverSocketChannel.configureBlocking(false);
		
		ByteBuffer buf = ByteBuffer.allocate(3);
		byte[] b = new byte[128];
		int len = -1;
		while(true) {
			SocketChannel socketChannel = serverSocketChannel.accept();
			//非阻塞模式，必须判断是不是null
			if (socketChannel != null) {
				//一次socket的请求大小可能大于buf缓冲区的大小，所以可能会读取很多次
				while((len = socketChannel.read(buf)) != -1){
					buf.flip();
					buf.get(b, 0, len);
					System.out.println(new String (b, 0, len));
					//或者一个个的读取
					/*while(buf.hasRemaining()) {
						System.out.println((char)buf.get());
					}*/
					buf.clear();
				}
			}
		}
	}
}
